import 'dart:ui';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/media_library_index_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_page.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/menu_dialog.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

/// 媒体库首页网格
///
/// @author: zengxiangxi
/// @createTime: 2/3/21 5:27 PM
/// @specialDemand:
class MediaLibraryIndexGridPage extends StatelessWidget {
  final List<MediaLibraryIndexListItemBean> list;

  final ValueChanged<MediaLibraryIndexListItemBean> onTap;

  final ValueChanged<MediaLibraryIndexListItemBean> onDelete;

  final ValueChanged<MediaLibraryIndexListItemBean> onUpateName;

  final bool canSelect;
  final String pageType;


  const MediaLibraryIndexGridPage({Key key, this.list, this.onTap,
    this.onDelete, this.onUpateName, this.canSelect, this.pageType})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    if(canSelect??false){
      return ScrollConfiguration(
          behavior: MyBehavior(),
          child: GridView.builder(
            padding: EdgeInsets.only(
                left: 15,
                right: 15,
                top: 3,
                bottom: getNavHeightDistance(context)),
            itemCount: list?.length ?? 0,
            physics: BouncingScrollPhysics(),
            shrinkWrap: true,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 5,
              crossAxisSpacing: 5,
              childAspectRatio: 1 / 1.2,
            ),
            itemBuilder: (BuildContext context, int index) {
              return _toGridItemWidget(context,list?.elementAt(index));
            },
          ));
    }else{
      return GridView.builder(
        padding: EdgeInsets.only(
            left: 15,
            right: 15,
            top: 3,
            bottom: getNavHeightDistance(context)),
        itemCount: list?.length ?? 0,
        physics: BouncingScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 5,
          crossAxisSpacing: 5,
          childAspectRatio: 1 / 1.2,
        ),
        itemBuilder: (BuildContext context, int index) {
          return _toGridItemWidget(context,list?.elementAt(index));
        },
      );
    }

  }

  Map<String,ValueChanged> _getMenuMap(BuildContext context,MediaLibraryIndexListItemBean itemBean){
    return {
      "重命名":(_){
        onUpateName?.call(itemBean);
      },
      "删除文件":(_){
        onDelete?.call(itemBean);
      }
    };
  }

  Widget _toGridItemWidget(BuildContext context, MediaLibraryIndexListItemBean itemBean) {
    double containerHeight = ((ScreenUtils.screenW(context) - 15 - 15) / 3);
    double width = ((((ScreenUtils.screenW(context) - 15 - 15) / 3) * 9) / 16);
    double height = 0;
    //不是16/9的图要重新布局
    bool resizeFlag = false;
    if (!StringUtils.isEmpty(itemBean?.picsize)) {
      List<String> sizeList = itemBean?.picsize?.split("*");
      int x = int.parse(sizeList[0]);
      int y = int.parse(sizeList[1]);
      double scale = x/y;
      height = width/scale;
      resizeFlag = true;
    }
    //是否需要模糊
    bool needBlurFlag = (containerHeight - height).abs() > 50;

    return ClickBackgroundWidget(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        onTap?.call(itemBean);
      },
      onLongPress: (detail){
        return MenuDialogUtils.showMenuDialog(context: context,longPressDetails: detail,itemMap: _getMenuMap(context,itemBean));
      },
      child: Column(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: AspectRatio(
              aspectRatio: 1,
              child: Container(
                color: Colors.black,
                child: Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    ((resizeFlag??false) && needBlurFlag)?
                    Stack(
                      alignment: Alignment.center,
                      children: [
                        // Container(
                        //     width: width,
                        //     height: containerHeight,
                        //     child: VgCacheNetWorkImage(
                        //       itemBean?.getCoverUrl() ?? "",
                        //       imageQualityType: ImageQualityType.middleDown,
                        //     )
                        // ),
                        // Container(
                        //   width: width,
                        //   height: containerHeight,
                        //   child: BackdropFilter(
                        //     filter: new ImageFilter.blur(sigmaX: 0, sigmaY: 5),
                        //     child: new Container(
                        //       // color: Colors.white.withOpacity(0.2),
                        //       color: Color(0x33FFFFFF).withOpacity(0.2),
                        //       width: width,
                        //       height: containerHeight,
                        //     ),
                        //   ),
                        // ),
                        Container(
                            width: width,
                            height: height,
                            child: VgCacheNetWorkImage(
                              itemBean?.getCoverUrl() ?? "",
                              imageQualityType: ImageQualityType.middleDown,
                            )
                        ),
                      ],
                    ):VgCacheNetWorkImage(
                      itemBean?.getCoverUrl() ?? "",
                      imageQualityType: ImageQualityType.middleDown,
                    ),
                    Positioned(
                      top: 5,
                      left: 5,
                      child: Offstage(
                        offstage: (itemBean?.attnum == null || itemBean.attnum <= 0),
                        child: Container(
                          width: 5,
                          height: 5,
                          decoration: BoxDecoration(
                              color: ThemeRepository.getInstance()
                                  .getMinorRedColor_F95355(),
                              shape: BoxShape.circle),
                        ),
                      ),
                    ),
                    // Positioned(
                    //   bottom: 0,
                    //   left: 0,
                    //   right: 0,
                    //   child: Container(
                    //     alignment: Alignment.centerLeft,
                    //     padding: const EdgeInsets.only(
                    //         left: 8, right: 8, bottom: 6, top: 10),
                    //     decoration: BoxDecoration(
                    //         gradient: LinearGradient(
                    //             begin: Alignment.topCenter,
                    //             end: Alignment.bottomCenter,
                    //             colors: [
                    //           Color(0x00000000),
                    //           Color(0x80000000)
                    //         ])),
                    //     child: Text(
                    //       itemBean?.picname ?? "",
                    //       maxLines: 1,
                    //       overflow: TextOverflow.ellipsis,
                    //       style: TextStyle(
                    //         color: Colors.white,
                    //         fontSize: 10,
                    //       ),
                    //     ),
                    //   ),
                    // ),
                    Offstage(
                      offstage: !(itemBean?.isVideo() ?? false),
                      child: Opacity(
                        opacity: 0.5,
                        child: Image.asset(
                          "images/video_play_ico.png",
                          width: 40,
                        ),
                      ),
                    ),
                    Positioned(
                      top: 0,
                      right: 0,
                      child: Offstage(
                        offstage: !(itemBean?.isVideo() ?? false),
                        child: Container(
                          width: 33,
                          height: 14,
                          decoration: BoxDecoration(
                              color: VgColors.INPUT_BG_COLOR,
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(4),
                                  topRight: Radius.circular(4))),
                          child: Center(
                            child: Text(
                              VgDateTimeUtils.getSecondsToMinuteStr(itemBean?.videotime) ?? "00:00",
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 9,
                                  height: 1.2
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    AnimatedOpacity(
                      duration: DEFAULT_ANIM_DURATION,
                      opacity:
                      itemBean.selectStatus??false
                          ? 0.3
                          : 0,
                      child: Container(
                        color: Colors.white,
                      ),
                    ),
                    Visibility(
                      visible: canSelect??false,
                      child: Positioned(
                        top: 8,
                        right: 8,
                        child: _toSelectWidget(itemBean?.selectStatus??false),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(vertical: 4),
              alignment: Alignment.topLeft,
              child: Text(
                // ("永久播放" == (itemBean?.getResumePlayInterval()??"剩余0天"))?"永久播放"
                //     :("已播放${itemBean?.getAlreadyPlayInterval()??"0天"}，${itemBean?.getResumePlayInterval()??"剩余0天"}"),
                itemBean?.getPlayTimeString(pageType: pageType),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: ThemeRepository.getInstance()
                      .getTextMinorGreyColor_808388(),
                  fontSize: 9,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _toSelectWidget(bool selectStatus){
    return AnimatedSwitcher(
      duration: DEFAULT_ANIM_DURATION,
      child:  Image.asset(
        selectStatus?"images/icon_select_delete.png":"images/icon_unselect_delete.png",
        width: 20,
      ),
    );
  }
}
